<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller {
	public function __construct() {
		parent::__construct();
		//$this->output->enable_profiler(TRUE);
		$this->load->helper('public');
		if (!isset($_SESSION['passid']) || empty($_SESSION['passid'])) {
			show_message('请登录', site_url('user/login').'?goto='.urlencode(current_url()));
			exit();
		}
		$this->load->library('form_validation');
		//设置表单错误分隔符，设置为空，直接输出即可
		$this->form_validation->set_error_delimiters('','');
		$this->load->model('member_model', 'member');
		$this->load->model('bbs_model', 'bbs');
		$this->load->helper('ip');	
	}
	public function index(){
		$this->load->view("home/index");
	}
	public function roleRule(){
		$data["action"] = "roleRule";
		$this->load->view("/home/roleRule", $data);
	}

	public function changeRole($uc_id){
		$roles = $this->member->get_roles($_SESSION["passid"]);
		if (empty($roles) || count($roles) == 0) {
			log_message("error", "changeRole, roles为空");
			show_error("对不起，无法更改角色登陆");
		}
		$uc_id = intval($uc_id);
		foreach ($roles as $key => $value) {
			$uc_ids[] = $value["uc_id"];
		}
		if (!in_array($uc_id, $uc_ids)) {
			log_message("error", "changeRole, uc_id不是该通行证下的");
			show_error("您切换的论坛用户并非绑定在您的家园账户下");
		}
		$synLoginCode = uc_user_synlogin($uc_id);
		show_message('登录成功'.$synLoginCode, $this->config->item('bbs_path'));
	}

	public function createrole() {
		$config = array(
				array(
						'field' => 'rolename',
						'label' => '论坛名',
						'rules' => 'tirm|required'
						)
				);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
		if ($this->form_validation->run() === FALSE) {
			$this->load->view('/user/createrole');
		} else {
			$rolename = $this->input->post('rolename');
			$member = $this->member->select_one_by_field('id', $_SESSION['passid']);
			$roles_num = $this->member->get_roles_num($_SESSION['passid']);
			
			if ($member['adminid'] == '0' && $roles_num > 0) {
				show_error('管理员才有创建马甲的权力');
			}
			//如果之前没有角色，新创建的角色就是默认角色，否则不是默认角色
			$isDefault = $roles_num == 0?1:0;

			$uc_id = uc_user_register($rolename, authcode($member["password"], "DECODE", $this->config->item("password_encode_key")),$member['email']);
			
			if ($uc_id == -1) {
				$data['error'] = '用户名不合法';
				$this->load->view('/user/createrole', $data);
				return;
			}
			
			if ($uc_id == -2) {
				$data['error'] = '包含不允许注册的词语';
				$this->load->view('/user/createrole', $data);
				return;
			}
			
			if ($uc_id == -3) {
				$data['error'] = '用户名已经存在';
				$this->load->view('/user/createrole', $data);
				return;
			}
			
			if ($uc_id == -4) {
				$data['error'] = 'Email 格式有误';
				$this->load->view('/user/createrole', $data);
				return;
			}
			
			if ($uc_id == -5) {
				$data['error'] = 'Email 不允许注册';
				$this->load->view('/user/createrole', $data);
				return;
			}
			
			if ($uc_id == -6) {
				$data['error'] = '该 Email 已经被注册';
				$this->load->view('/user/createrole', $data);
				return;
			}
			
			
			$roledata = array(
					'pass_id'     => $_SESSION['passid'],
					'uc_id'       => $uc_id,
					'uc_name'     => $rolename,
					'uc_password' => $member["password"],
					'uc_email'    => $member["email"],
					'regdate'     => time(),
					'isdefault'   => $isDefault
					);
			$roleId = $this->member->create_role($roledata);
			
			if (empty($roleId)) {
				show_error('创建用户名失败，请联系管理员');
			}

			$current_time = time();

			$common_member = array(
				"uid"        => $uc_id,
				"username"   => $rolename,
				"password"   => md5(rand(1000,99999999)),
				"adminid"    => '0',
				"groupid"    => '10',
				"timeoffset" => "9999",
				"email"      => $member['email']
				);
			$id = $this->bbs->insert("common_member", $common_member);


			$common_memberfields = array(
				"uid" => $uc_id
				);
			$id = $this->bbs->insert("common_member_profile", $common_memberfields);

			
			$memberStatus = array(
				"uid" => $uc_id,
				"regip" => get_client_ip()
				);
			$id = $this->bbs->insert("common_member_status", $memberStatus);

			$memberFieldForum = array(
				"uid" => $uc_id
				);
			$id = $this->bbs->insert("common_member_field_forum", $memberFieldForum);

			$memberFieldHome = array(
				"uid" => $uc_id
				);
			$id = $this->bbs->insert("common_member_field_home", $memberFieldHome);

			$memberCount = array(
				"uid" => $uc_id
				);
			$id = $this->bbs->insert("common_member_count", $memberCount);

			$synLoginCode = uc_user_synlogin($uc_id);
			show_message('创建成功'.$synLoginCode, $this->config->item('bbs_path'));
		}
	}
	//绑定图书馆页面
	public function lib() {
		$view["action"] = "lib";
		$config = array(
			array(
				"field" => "password",
				"label" => "password",
				"rules" => "trim|required"
				)
			);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');

		if ($this->form_validation->run() == FALSE) {
			$hasLibPassword = $this->member->get_lib_password($_SESSION["stuID"]);
			
			if ($hasLibPassword == FALSE) {
				$view["hasLibPassword"] = -1;
			} else {
				if (!checkLibPassword($_SESSION["stuID"], authcode($hasLibPassword["password"], "DECODE", $this->config->item("password_encode_key")))) {
					$view["hasLibPassword"] = -2;
				} else {
					$view["hasLibPassword"] = 1;
				}				
			}
			$this->load->view('home/lib', $view);
		} else {
			$password = $this->input->post("password");

			if (!checkLibPassword($_SESSION["stuID"], $password)) {
				unset($password);
				unset($encodePassword);
				$view['success'] = "密码不正确";
				$view["hasLibPassword"] = -3;
				$this->load->view("/home/lib", $view);
				return ;
			}

			$encodePassword = authcode($password, "encode", $this->config->item("password_encode_key"));

			if ($this->member->bind_lib_account($_SESSION["stuID"], $encodePassword)) {
				unset($password);
				unset($encodePassword);
				$view['success'] = "绑定成功";
				$view["hasLibPassword"] = 1;
				$this->load->view("/home/lib", $view);
				//echo "success";
			} else {
				show_error("图书馆绑定失败，插入数据库失败");
			}
		}
	}

	public function roles(){
		$data["action"] = "roles";
		$data["roles"] = $this->member->get_roles($_SESSION["passid"]);
		//提取出所有角色的id
		if (!empty($data["roles"]) && is_array($data["roles"]) && count($data["roles"]) > 0) {
			foreach ($data["roles"] as $key => $value) {
				$roles[] = $value["id"];
			}
		}
		
		$config = array(
			array(
				"field" => "roles[]",
				"label" => "论坛角色",
				"rules" => "trim|required"
				)
			);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');

		if ($this->form_validation->run() == FALSE) {
			$this->load->view('home/roles', $data);
		} else {
			$role = $this->input->post("roles");

			if (empty($role) || !is_array($role)) {
				log_message("error", "roleId参数错误");
				show_error("role参数为空, /home/roles");
			}

			$role = intval($role[0]);
			if (!in_array($role, $roles)) {
				log_message("error", "roleId参数被修改");
				show_error("roleid参数错误， /home/roles");
			}
			
			if ($this->member->set_default_role($_SESSION["passid"], $role)) {
				$data["success"] = "修改默认角色成功";
				$data["roles"] = $this->member->get_roles($_SESSION["passid"]);
				$this->load->view("/home/roles", $data);
			} else {
				$data["success"] = "修改失败";
				$data["roles"] = $this->member->get_roles($_SESSION["passid"]);
				$this->load->view("/home/roles", $data);
			}
		}
	}
	/*
	验证邮箱，往邮箱中发一封信
	 */
	public function mail(){
		header("Content-type:text/html;charset=utf-8");
		//$data["action"] = "email";
		
		$action = $this->input->get("action");

		switch ($action) {
			case 'register':
				# 如果是注册页发生的邮箱发送，点击链接后就跳转到图书馆密码绑定页面
				$url = site_url("/home/guid");
				break;
			case 'modify':
				$url = site_url("/home/email");
				break;
			case 'active':
				$url = site_url("/home/email/changeEmail");
				break;
			default:
				$url = site_url("/home/email/changeEmail");
				break;
		}

		if (!isset($_SESSION["needMail"]) || $_SESSION["needMail"] != "1") {
			unset($_SESSION["needMail"]);
			show_error("参数缺失");
			return ;
		}
		unset($_SESSION["needMail"]);
		if (!isset($_SESSION["toMail"]) || empty($_SESSION["toMail"])) {
			$member = $this->member->select_one_by_field("id", $_SESSION["passid"]);
		
			$checkemail = $this->member->selectNotCheckMail($_SESSION["passid"]);
			if ($checkemail == FALSE) {
				$mail = $member["email"];
			} else {
				$mail = $checkemail["mail"];
			}
		} else {
			
			$mail = $_SESSION["toMail"];
		}
		
		if (!$this->member->send_mail($_SESSION["passid"], $mail, $url)) {
			$view["info"] = "发送邮件失败";
			log_message("error", "发送邮件失败");
			unset($_SESSION["toMail"]);
			show_error("发送邮件失败,请联系管理员");
		} else {
			$view = array();
			$view["email"] = encode_email_address($mail);
			$this->load->view("/home/email/sendSuccess", $view);
			unset($_SESSION["toMail"]);
		}
	}

	/*
		邮箱管理页面
	 */
	public function changeEmail() {
		$config = array(
			array(
				"field" => "HduPassword",
				"label" => "教务系统密码",
				"rules" => "required"
				),
			array(
				"field" => "newEmail",
				"label" => "新邮箱",
				"rules" => "required|valid_email|is_unique[member.email]"
				)
			);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message("valid_email", "邮箱地址格式不正确");
		$this->form_validation->set_message("is_unique", "该邮箱已经被人使用");
		if ($this->form_validation->run() == FALSE) {
			$this->load->view("/home/email/changeEmail");
		} else {
			$password = $this->input->post("HduPassword");
			$newEmail = $this->input->post("newEmail");

			if (!checkHduPassword($_SESSION["stuID"], $password)) {
				$view["error"] = "教务系统密码不正确，请重试";
				$this->load->view("/home/email/changeEmail", $view);
				return;
			}
			$_SESSION["needMail"] = 1;
			$_SESSION["toMail"] = $newEmail;

			redirect("/home/mail?action=modify");
			/*if ($this->member->send_mail($_SESSION["passid"], $newEmail)) {
				echo "email is sended;";
			} else {
				echo "email send failed";
			}*/
		}
	}

	public function email() {
		$act = $this->input->get("act");

		switch ($act) {
			case "modify":
				//调用修改邮箱页面
				redirect("/home/changeEmail");
				break;
			case "active":
				//给未激活邮箱发送激活邮件
				$_SESSION["needMail"] = 1;
				redirect("/home/mail?action=active");
				break;
			default:
				$member = $this->member->select_one_by_field("id", $_SESSION["passid"]);
				$view["email"] = encode_email_address($member["email"]);
				if ($member["emailstatus"] == 0) {
					$checkemail = $this->member->selectNotCheckMail($_SESSION["passid"]);
					if ($checkemail == FALSE) {
						
					} else {
						$view["email"] = encode_email_address($checkemail["mail"]);
					}
				}
				
				$view["emailActive"] = $member["emailstatus"];
				$view["action"] = "email";
				$this->load->view("/home/email/email", $view);

				break;
		}
	}

	public function changePassword() {
		$config = array(
			array(
				"field" => "oldpassword",
				"label" => "旧密码",
				"rules" => "trim|required|min_length[6]|max_length[20]"
				),
			array(
				"field" => "newpassword",
				"label" => "新密码",
				"rules" => "trim|required|min_length[6]|max_length[20]"
				),
			array(
				"field" => "repassword",
				"label" => "重复密码",
				"rules" => "trim|required|matches[newpassword]|min_length[6]|max_length[20]"
				)
			);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
		$this->form_validation->set_message('min_length', '<i class="icon-exclamation-sign"></i>%s长度至少为%s位');
        $this->form_validation->set_message('max_length', '<i class="icon-exclamation-sign"></i>%s长度至多为%s位');
		$this->form_validation->set_message('matches', '<i class="icon-exclamation-sign"></i>请确保密码一致');

		if ($this->form_validation->run() == FALSE) {
			$this->load->view("/home/changePassword");
		} else {
			$oldpassword = $this->input->post("oldpassword");
			$newpassword = $this->input->post("newpassword");

			if ($oldpassword == $newpassword) {
				$data["error"] = "请确保修改后的密码和原有的密码不一致";
				$this->load->view("/home/changePassword", $data);
				return;
			}
			$member = $this->member->select_one_by_field("id", $_SESSION["passid"]);
			if (empty($member)) {
				show_error("该用户不存在");
			} else {
				if ($member["password"] != rd_encode_password($oldpassword)) {
					$data["error"] = "原有密码不正确";
					$this->load->view("/home/changePassword", $data);
					return;
				} else {
					if ($this->member->changePassword($member["email"], rd_encode_password($oldpassword))) {
						$data["success"] = "修改密码成功";
						$this->load->view("/home/changePassword", $data);
						return;
					}
				}
			}
		}
	}
	//应用页面
	public function app(){
		$apps = $this->member->selectAllUseApps($_SESSION["passid"]);
		$view["apps"] = $apps;
		$this->load->view("/home/apps", $view);
	}

	public function deBind($appid) {
		$appid = intval($appid);

		$r = $this->member->deBind($appid, $_SESSION["passid"]);

		if (is_array($r)) {
			if ($r[0] == 1) {
				show_message("解除绑定成功", site_url("/home/app"));
			} else {
				show_message($r[1], site_url("/home/app"));
			}
		}
	}

	public function bind($appid = 0) {
		$appid = intval($appid);
		if ($appid == 0) {
			show_404();
		}
		$r = $this->member->selectFromTable("member_app", "id", $appid);
    	if (empty($r)) {
    		show_error("该应用不存在");
    	} else {
    		$data["app"] = $r;
        	$data["field"] = array("学号");
    	}
		$config = array(
			array(
				"field" => "stuID",
				"label" => "学号",
				"rules" => "trim|required|numeric" //tdo
				),
			array(
				"field" => "password",
				"label" => "密码",
				"rules" => "trim|required|min_length[6]|max_length[30]"
				),
			);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
        $this->form_validation->set_message('check_stuID', '<i class="icon-exclamation-sign"></i>学号格式不正确');

        if ($this->form_validation->run() == FALSE) {
			$this->load->view("/home/bind", $data);
        } else {
        	$stuID = $this->input->post("stuID");
        	$password = $this->input->post("password");
        	$checkPassword = 0;
        	switch($appid) {
        		case 1:
        			if (checkHduPassword($stuID, $password)) {
        				$checkPassword = 1;
        			}
        			break;
        		case 2:
        			if (checkLibPassword($stuID, $password)) {
        				$checkPassword = 1;
        			}
        			break;
        	}

        	if ($checkPassword == 0) {
        		$data["error"] = $r["appname"]."密码错误";
        		$this->load->view("/home/bind", $data);
        		return;
        	}

        	$encodePassword = authcode($password, "encode", $this->config->item("password_encode_key"));
        	$bindresult = $this->member->bindApp($appid, $_SESSION["passid"], $stuID, "", "", $password);
        	if (is_array($bindresult)) {
        		if ($bindresult[0] == 1) {
        			$data["success"] = "绑定成功";
        			$this->load->view("/home/bind", $data);
        			return;
        		} else {
					$data["error"] = $bindresult[1];
	        		$this->load->view("/home/bind", $data);
	        		return;
        		}
        	} else {
        		$data["error"] = "数据库出错，请联系管理员";
        		$this->load->view("/home/bind", $data);
        		return;
        	}
        	
        }
	}

	public function appStatus($appid = 0) {
		$appid = intval($appid);
		
	}
	public function check_stuID($stuID) {
        $pattern = "/^[0-9]{4,9}$/u";
 
        if (preg_match($pattern, $stuID)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}